import tinymce from 'tinymce/tinymce'

/**
 * 根据节点信息找到节点自身以及下面所有层级的节点
 * 并全部删除
 */

const mapItemOrders = {
  chapter: 0,
  item1: 1,
  item2: 2,
  item3: 3,
  item4: 4
}

export default function (nodeInfo) {
  const editor = tinymce.activeEditor
  const nodes = editor.dom.select('#tinymce>.page-wrapper div[data-id=' + nodeInfo.dataId + ']')
  if (nodes.length === 1) {
    let currentNode = nodes[0],
      nextNode = editor.dom.getNext(currentNode, '*'),
      shouldRemoveNodes = []
    const curDataOrder = mapItemOrders[currentNode.dataset.type]
    while (currentNode) {
      shouldRemoveNodes.push(currentNode)

      if (nextNode) {
        currentNode = nextNode
        nextNode = editor.dom.getNext(currentNode, '*')
      } else {
        currentNode = null
        break
      }

      const { type } = currentNode?.dataset || {}
      if (type) {
        if (mapItemOrders[type] <= curDataOrder) {
          break
        }
      }
    }
    editor.dom.remove(shouldRemoveNodes)
  }
}
